from django.shortcuts import render

from rest_framework import generics
from .models import Course,Stage,Chapter,Section
from .serializers import CourseSerializer,StageSerializer,ChapterSerializer,SectionSerializer,StageDetailSerializer,ChapterDetailSerializer
from rest_framework.pagination import PageNumberPagination
from django.db.models import Count

#自定义分页器
class CourseResultPagiation(PageNumberPagination):
    page_size = 2  #默认每页显示多少条数据
    max_page_size = 5  #前端控制在每页显示多少条时，最多不能超过5
    page_query_param = 'page'  #前端在查询字符串的关键字  指定显示第几页的名字，不指定时默认page
    page_size_query_param = 'page_size'  #前端在查询字符串的关键字名字，是用来控制每页显示多少条的关键字

#课程查询
class CourseInfoView(generics.ListAPIView):
    queryset = Course.objects.annotate(
        stages_count = Count('stages'),
        chapter_count = Count('stages__chapter'),
        section_count = Count('stages__chapter__section')
    ).values(
        'name','learn_info','learn_style','learn_time','supervision','icon','brief','level','stages_count',
        'chapter_count','section_count'
    )
    serializer_class = CourseSerializer
    #分页
    pagination_class = CourseResultPagiation

#课程阶段
class StageListView(generics.ListAPIView):
    queryset = Stage.objects.all()
    serializer_class = StageSerializer
    #增加过滤，根据课程名称过滤
    filterset_fields = ('course',)

#阶段章节
class ChapterView(generics.ListAPIView):
    queryset = Chapter.objects.all()
    serializer_class = ChapterSerializer
    #增加过滤
    filterset_fields = ('stage',)

#章节小节
class SectionView(generics.ListAPIView):
    queryset = Section.objects.all()
    serializer_class = SectionSerializer
    #增加过滤
    filterset_fields = ('chapter',)

#课程阶段详情分页
class StagePagiation(PageNumberPagination):
    page_size = 2
    page_query_param = 'page'
    page_size_query_param = 'page_size'

#课程阶段详情
class StageDetailView(generics.RetrieveAPIView):
    queryset = Stage.objects.all()
    serializer_class = StageDetailSerializer

    pagination_class = StagePagiation

